package com.briup.corejava.day20;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * TCP协议下的服务器搭建
 */
public class TcpServer {
    public static void main(String[] args) {
        // 创建ServerSocket对象
        ServerSocket serverSocket = null;
        Socket socket = null;
        int port = 8888;
        // 可以使用内部类，也可以使用外部类
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("服务器启动，正在监听"+port+"端口");
            int i = 1;
            while(true) {
                socket = serverSocket.accept();
                // 每得到一个socket就创建一条子线程
                Thread t = new ClientHandler(socket,"客户端"+(i++));
                t.start();
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (serverSocket != null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
class ClientHandler extends Thread{

    private Socket socket;

    public ClientHandler(Socket socket,String name){
        super(name);
        this.socket = socket;
    }

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        try {
            // 从socket里读取数据
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            Object o = ois.readObject();
            User u = null;
            if (o instanceof User) {
                u = (User) o;
            }
            // 对u进行服务器的处理验证
            // 将stu.txt的文件内容转成集合
            BufferedReader br = new BufferedReader(
                    new FileReader(
                            "src/com/briup/corejava/day20/stu.txt"
                    )
            );
            String line = null;
            List<User> list = new ArrayList<>();
            while ((line = br.readLine()) != null) {
                // 将每一行数据以.进行分割
                String[] split = line.split("[.]");
                User user = new User(split[1], split[2]);
                user.setId(Integer.parseInt(split[0]));
                list.add(user);
            }
            // 定义变量记录响应的信息
            String result = "";
            // 先匹配账号是否存在，再匹配密码是否一致
            for (User user : list) {
                assert u != null; // 断言的应用场景
                if (u.getUsername().equals(user.getUsername())) {
                    if (u.getPassword().equals(user.getPassword())) {
                        result = name+"登陆成功";
                        u = user;
                        break;
                    } else {
                        result = "账号密码不匹配";
                    }
                } else {
                    result = "用户不存在";
                }
            }
            // 将结果输出到客户端
            PrintWriter pw = new PrintWriter(socket.getOutputStream());
            pw.println(result);
            pw.flush();

            String str = (String) ois.readObject();
            System.out.println(str);

            ois.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}